package com.yunxin.admin.system.api.system;

import com.yunxin.common.result.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author zero°
 * @since 2023-05-23
 */
@RestController
@RequestMapping({"${server.error.path:${error.path:/error}}"})
public class MyErrorController extends BasicErrorController {

    public MyErrorController(ServerProperties serverProperties) {
        super(new DefaultErrorAttributes(), serverProperties.getError());
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        Map<String, Object> map = new HashMap<>(4);
        Map<String, Object> originalMsgMap = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        String path = (String) originalMsgMap.get("path");
        String error = (String) originalMsgMap.get("error");
        String message = (String) originalMsgMap.get("message");
        ErrorResponse errorResponse = new ErrorResponse();
        errorResponse.setPath(path);
        errorResponse.setError(error);
        errorResponse.setMessage(message);
        map.put("code", ResultCode.SYSTEM_EXECUTION_ERROR.getCode());
        map.put("data", errorResponse);
        map.put("msg", status + " 异常");
        return new ResponseEntity<>(map, status);
    }

    @Data
    static class ErrorResponse {

        private String path;

        private String error;

        private String message;
    }
}
